/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

#include "../Types.h"
#include "string.h"
#include "U32UTF8.h"
#include "BigEndianUnsignedInteger.h"

type_name u32utf8_name = { "u32utf8" };

int u32utf8_read(type_input_stream * in, type_element * element)
{
	/*The below line won't work because we don't know what U8BID
	//is registered as in the remote system.
	//Byte id = (Byte) in.readObject( TypeMapCore.U8BID );
	//We can either use the element to find the reference object
	//in the sequence definition or cheat and just read a byte.
	//unsigned int * id = (unsigned int *) in.readObject( BigEndianUnsignedInteger::TYPENAME );
	 */
	type_input_read_named_object(in, &uint32_name );
	
	uint32_t length = type_stack_get_u32( type_input_stack(in) );

	if ( length > 0 )
	{

		char * str = (char *) type_malloc( length );
		
		int toRead = length;
		int haveRead = 0;
		int read = 0;
		
		while( toRead > 0 )
		{
			read = type_input_read_buffer( in, str+haveRead, toRead );
			if ( read <= 0 )
			{
				type_input_set_error( in, 10 );
				return TYPE_EOF;
			}
			toRead = toRead - read;
			haveRead += read;
		}
		
		str[length]=0;
		
		type_stack_set_ptr( &in->stack, element, str );
	}
	else
	{
		char * str = (char *) type_malloc( 1 );
		str[0] = 0;
		type_stack_set_ptr( &in->stack, element, str );
	}
	return TYPE_OK;
}


int u32utf8_write(type_output_stream * out, void * o, type_element * element )
{
	char * str = (char *) o;
	int size = 0;
	
	if ( o == NULL )
	{
		type_output_write_named_object( out, &uint32_name, &size );
		return TYPE_OK;
	}

	size = strlen( str );

		
	type_output_write_named_object(out, &uint32_name, &size );
	type_output_write_buffer( out, str, size );
	return TYPE_OK;
	
}
